# -*- coding: utf-8 -*-

"""
Datetime: 2020/07/23
Author: Zhang Yafei
Description: 图鉴验证码 http://daredian.cn/
"""
import base64
import json
from io import BytesIO
from sys import version_info
from urllib.parse import parse_qs, urlparse
from lxml import etree

import requests
from PIL import Image
import json
import requests

uname = '你的用户名'
pwd = '密码'


def save_image_to_file(response, file_name):
    with open(file_name, mode='wb') as f:
        f.write(response.content)


def base64_api(img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"], result['data']['id']
    else:
        return result["message"], result['data']['id']


def check_validate_code_pic(topic_url, img_url):
    headers = {
            'Host': 'www.dxy.cn',
            'Origin': 'http://www.dxy.cn',
            'Referer': 'http://www.dxy.cn/bbs/validation',
            'Cookie': 'DXY_USER_GROUP=63; __auc=ca4a673d173746d32cbbeca9249; _ga=GA1.2.1989255604.1595386166; CLASS_CASTGC=146f361ccb637797b810e7e2328da5fff0605920d9642d4bbee447b01549249787dcf249fcba8e188be34b18d84f64a065e145c9dfaa7926fdc5c615144d617d7ba2e9371f7e928ee08ba85c3446c6a32bbda0e2f137a2f41e9cbe7ba30aefa7136219eee50aec04ab8c61eb1055ee470396f4486cc8f9e9ccc2e5af144ea0bf8ddba7280ba761f714eab85f13513c52848d2707b1be6e68a4a59b53ae8fa59c3ca524c67ac52ff7518e85d40a21df8d7b8ce33294c438e128026afa338ec24865c8afaa78d9f64d434ecbc4da0054b6fee44c76a243a122017ce91b0557b784d40be788bc15b361207b4fd6f69671a1cbee08f94ede72294f54e01c3b074e5a; JUTE_BBS_DATA=49798dd5282ede3bc43bd853b52aff9a1dc750801848826068ae67a5adecdd2a0dfb1ad527cf8331b805f0eeb3f7f62422b83b82525c1e3706bd63b1d9ef0f614072c37a3ef5d311926c003ba59fb5d5; ifVisitOldVerBBS=true; route=fe9340375d898dc58dc46edbbdbb48f8; route_bbs=d183b59af94599ac5496eae0a79bc70f; dxy_da_cookie-id=3cb8b04f3626982530333173874a15971595470988552; JUTE_SESSION_ID=ac5d913a-22c3-478f-8254-7cf64669699f; JUTE_TOKEN=6ce4333d-1e0a-48cd-af1f-8b26ed55d4e4; cms_token=f52fb742-cc35-4aec-b186-69f7f98a2fe4; Hm_lvt_8a6dad3652ee53a288a11ca184581908=1595414051,1595470987,1595501771,1595520015; __asc=63bc4c541737c676aca74452e80; __utma=1.1989255604.1595386166.1595520020.1595520020.1; __utmc=1; __utmz=1.1595520020.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); Hm_lpvt_8a6dad3652ee53a288a11ca184581908=1595520958; __utmb=1.33.9.1595520959282; CMSSESSIONID=BEC94C113534CD3D7BBC5866272269E9-n2; JUTE_SESSION=c60636c249b07a0800b0f8fd8f284a382683f74376827ded7e32a706967e09b74a41ebd2e52b5e934b256040bdd27899d572c01064e0b36a9dae061c53371eb2d58cfae5a80a7bdd',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
    }
    done = topic_url.replace('http://www.dxy.cn', '')
    r = parse_qs(urlparse(img_url).query)['r'][0]
    response = requests.get(img_url)
    file_name = f'utils/images/{r}.jpg'
    save_image_to_file(response, file_name)
    img = Image.open(file_name)
    result, res_id = base64_api(img=img)
    data = {'done': done, 'code': result}
    response = requests.post('http://www.dxy.cn/bbs/validation', data=data, headers=headers)
    # print(f'{file_name}\t识别验证码为：{result}')
    html = etree.HTML(response.text)
    if html.xpath('//img[@id="codepic"]'):
        result = reportError(id=res_id)
        print('验证码识别 错误\t', result)
    else:
        print('验证码识别 正确')



def reportError(err_id):
    data = {"id": err_id}
    result = json.loads(requests.post("http://api.ttshitu.com/reporterror.json", json=data).text)
    if result['success']:
        return "报错成功"
    else:
        return result["message"]


if __name__ == "__main__":
    url = 'http://www.dxy.cn/bbs/topic/43682705'
    done = url.replace('http://www.dxy.cn', '')
    img_url = 'http://www.dxy.cn/bbs/code.jpg?r=1595521248206'
    r = parse_qs(urlparse(img_url).query)['r'][0]
    response = requests.get(img_url)
    file_name = f'images/{r}.jpg'
    save_image_to_file(response, file_name)
    img = Image.open(file_name)
    result, res_id = base64_api(img=img)
    print(result, res_id)
    # data = {'done': done, 'code': result}
    data = {'done': done, 'code': 'sasas'}
    headers = {
            'Host': 'www.dxy.cn',
            'Origin': 'http://www.dxy.cn',
            'Referer': 'http://www.dxy.cn/bbs/validation',
            'Cookie': 'DXY_USER_GROUP=63; __auc=ca4a673d173746d32cbbeca9249; _ga=GA1.2.1989255604.1595386166; CLASS_CASTGC=146f361ccb637797b810e7e2328da5fff0605920d9642d4bbee447b01549249787dcf249fcba8e188be34b18d84f64a065e145c9dfaa7926fdc5c615144d617d7ba2e9371f7e928ee08ba85c3446c6a32bbda0e2f137a2f41e9cbe7ba30aefa7136219eee50aec04ab8c61eb1055ee470396f4486cc8f9e9ccc2e5af144ea0bf8ddba7280ba761f714eab85f13513c52848d2707b1be6e68a4a59b53ae8fa59c3ca524c67ac52ff7518e85d40a21df8d7b8ce33294c438e128026afa338ec24865c8afaa78d9f64d434ecbc4da0054b6fee44c76a243a122017ce91b0557b784d40be788bc15b361207b4fd6f69671a1cbee08f94ede72294f54e01c3b074e5a; JUTE_BBS_DATA=49798dd5282ede3bc43bd853b52aff9a1dc750801848826068ae67a5adecdd2a0dfb1ad527cf8331b805f0eeb3f7f62422b83b82525c1e3706bd63b1d9ef0f614072c37a3ef5d311926c003ba59fb5d5; ifVisitOldVerBBS=true; route=fe9340375d898dc58dc46edbbdbb48f8; route_bbs=d183b59af94599ac5496eae0a79bc70f; dxy_da_cookie-id=3cb8b04f3626982530333173874a15971595470988552; JUTE_SESSION_ID=ac5d913a-22c3-478f-8254-7cf64669699f; JUTE_TOKEN=6ce4333d-1e0a-48cd-af1f-8b26ed55d4e4; cms_token=f52fb742-cc35-4aec-b186-69f7f98a2fe4; Hm_lvt_8a6dad3652ee53a288a11ca184581908=1595414051,1595470987,1595501771,1595520015; __asc=63bc4c541737c676aca74452e80; __utma=1.1989255604.1595386166.1595520020.1595520020.1; __utmc=1; __utmz=1.1595520020.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); Hm_lpvt_8a6dad3652ee53a288a11ca184581908=1595520958; __utmb=1.33.9.1595520959282; CMSSESSIONID=BEC94C113534CD3D7BBC5866272269E9-n2; JUTE_SESSION=c60636c249b07a0800b0f8fd8f284a382683f74376827ded7e32a706967e09b74a41ebd2e52b5e934b256040bdd27899d572c01064e0b36a9dae061c53371eb2d58cfae5a80a7bdd',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
    }
    response = requests.post('http://www.dxy.cn/bbs/validation', data=data, headers=headers)
    html = etree.HTML(response.text)
    if html.xpath('//img[@id="codepic"]'):
        print('验证码识别 错误')
    else:
        print('验证码识别 正确')

    result = reportError(err_id=res_id)
    print(result)
